package yz;

/**
 * [面试题 16.04. 井字游戏](https://leetcode-cn.com/problems/tic-tac-toe-lcci/)
 *
 * @author Yz
 * @since 2022-09-22 19:47
 */
public class LeetCode1604_TicTacToe {
    public String tictactoe(String[] board) {
        int m = board.length;
        char[][] array = new char[m][m];
        boolean flag = false;
        for (int i = 0; i < m; i++) {
            String string = board[i];
            if (!flag) {
                if (string.contains(" ")) {
                    flag = true;
                }
            }
            char[] chars = string.toCharArray();
            array[i] = chars;
            if (isWin(chars)) {
                return chars[0] + "";
            }
        }
        char[] clos = new char[m];
        char[] dj1 = new char[m];
        char[] dj2 = new char[m];
        for (int i = 0; i < m; i++) {
            dj1[i] = array[i][i];
            dj2[i] = array[i][m - 1 - i];
            for (int k = 0; k < m; k++) {
                clos[k] = array[k][i];
            }
            if (isWin(clos)) {
                return clos[0] + "";
            }
        }
        if (isWin(dj1)) {
            return dj1[0] + "";
        }
        if (isWin(dj2)) {
            return dj2[0] + "";
        }
        if (flag) {
            return "Pending";
        }
        return "Draw";
    }
    
    private boolean isWin(char[] chars) {
        if (chars[0] == ' ') {
            return false;
        }
        for (char aChar : chars) {
            if (chars[0] != aChar) {
                return false;
            }
        }
        return true;
    }
}
